//
//  ISCallSettingViewController.m
//  iPhoneSafety
//
//  Created by dlon 2018/12/31.
//  Copyright © 2018年 com.li.ding. All rights reserved.
//

#import "ISCallSettingViewController.h"
#import "ISRingServer.h"
#import "ISCallSettingCollectionViewCell.h"
#import "ISCallVoiceCollectionViewCell.h"
#import "ISCallSwitchCollectionViewCell.h"
#import <libextobjc/EXTScope.h>
#import "NWLazyProperty.h"
#import "ISPickerView.h"
#import "UIColor+NWHex.h"
#import "UIFont+NWWeight.h"
#import <BlocksKit/BlocksKit.h>
#import "ISRingServer.h"

@interface ISCallSettingViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, strong) ISPickerView *picker;
@property (nonatomic, strong) ISPickerView *delayPicker;
@end

@implementation ISCallSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    self.fd_interactivePopDisabled = YES;
    
    self.title = @"警报设置";
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName: [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium]};
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.titleTextAttributes = @{ NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium]};
}


- (void)loadData {
    [self.list removeAllObjects];
    
    //警报延时
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSettingCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"警报延时";
        if ([ISRingServer shareInstance].config.delayTime == 0) {
            dict[@"des"] = @"立即报警";
        } else {
            dict[@"des"] = [NSString stringWithFormat:@"%ld秒",[ISRingServer shareInstance].config.delayTime];
        }

        dispatch_block_t block = ^(void) {
            NSMutableArray *list = @[].mutableCopy;
            NSInteger idx = 0;
            for (int i = 0; i < 7; i ++) {
                if (i == 0) {
                    [list addObject:@{@"obj" : @(i), @"title" : @"立即报警"}];
                } else {
                    [list addObject:@{@"obj" : @(i), @"title" : [NSString stringWithFormat:@"%d秒",i]}];
                }
                if ([ISRingServer shareInstance].config.delayTime == i) {
                    idx = i;
                }
            }
            [self.delayPicker showWithList:list selectIdx:idx];
        };
        dict[@"block"] = block;

        [self.list addObject:dict];
    }
    
    //警报铃声
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSettingCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"警报铃声";
        dict[@"des"] = [ISRingServer shareInstance].config.nowInfo.soundName;
        @weakify(self)
        dispatch_block_t block = ^(void) {
            @strongify(self)
            NSArray *list = [[ISRingServer shareInstance].systemSounds bk_map:^id(ISSoundInfomation *obj) {
                return @{@"title" : obj.soundName, @"obj" : obj};
            }];
            NSUInteger idx = 0;
            for (ISSoundInfomation *info in [ISRingServer shareInstance].systemSounds) {
                if ([info.soundName isEqualToString:[ISRingServer shareInstance].config.nowInfo.soundName] && [info.soundUrl.absoluteString isEqualToString:[ISRingServer shareInstance].config.nowInfo.soundUrl.absoluteString]) {
                    idx = [[ISRingServer shareInstance].systemSounds indexOfObject:info];
                    break;
                }
            }
            [self.picker showWithList:list selectIdx:idx];
            if (self.picker.selectBlock) {
                self.picker.selectBlock(list[idx], idx);
            }
        };
        dict[@"block"] = block;
        [self.list addObject:dict];
    }
    
    //警报音量
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallVoiceCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"警报音量";
        dict[@"value"] = @([ISRingServer shareInstance].config.voice);
        dict[@"actionBlock"] = ^void(CGFloat value) {
            [ISRingServer shareInstance].config.voice = value;
        };
        [self.list addObject:dict];
    }
    
    //警报震动
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSwitchCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"警报震动";
        dict[@"isOn"] = @([ISRingServer shareInstance].config.shock);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [ISRingServer shareInstance].config.shock = value;
        };

        [self.list addObject:dict];
    }
    
    [self.collectionView reloadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.frame = CGRectMake(0, self.view.safeAreaInsets.top, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - self.view.safeAreaInsets.top);
    } else {
        self.collectionView.frame = CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 64);
    }
    
}

#pragma mark - action
- (void)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    dispatch_block_t block = viewModel[@"block"];
    if (block) {
        block();
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSDictionary *viewModel = self.list[indexPath.row];
    NSString *type = viewModel[@"type"];
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:type forIndexPath:indexPath];
    
    if ([type isEqualToString:@"ISCallSettingCollectionViewCell"]) {
        ISCallSettingCollectionViewCell *settingCell = (ISCallSettingCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];
        settingCell.desLabel.text = viewModel[@"des"];
    }
    
    if ([type isEqualToString:@"ISCallSwitchCollectionViewCell"]) {
        ISCallSwitchCollectionViewCell *settingCell = (ISCallSwitchCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];
        settingCell.switchView.on = [viewModel[@"isOn"] boolValue];
        settingCell.actionBlock = viewModel[@"actionBlock"];
    }
    
    if ([type isEqualToString:@"ISCallVoiceCollectionViewCell"]) {
        ISCallVoiceCollectionViewCell *settingCell = (ISCallVoiceCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];

        settingCell.slider.value = [viewModel[@"value"] floatValue];
        settingCell.actionBlock = viewModel[@"actionBlock"];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.list.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    
    return CGSizeMake(CGRectGetWidth(collectionView.frame), [viewModel[@"height"] doubleValue]);
}

#pragma mark - set & get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[ISCallSwitchCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallSwitchCollectionViewCell"];
        [_collectionView registerClass:[ISCallVoiceCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallVoiceCollectionViewCell"];
        [_collectionView registerClass:[ISCallSettingCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallSettingCollectionViewCell"];
        
        
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _collectionView;
}

NWLazyPropertyWithInit(NSMutableArray, list, {
    
})

NWLazyPropertyWithInit(ISPickerView, picker, {
    _picker.selectBlock = ^(id item, NSInteger row) {
        ISSoundInfomation *info = item[@"obj"];
        [[ISRingServer shareInstance] playWithSound:info];
    };
    @weakify(self)
    _picker.completeBlock = ^(id item, NSInteger row) {
        ISSoundInfomation *info = item[@"obj"];
        [[ISRingServer shareInstance] selectSound:info];
        @strongify(self)
        [self loadData];
    };
})

NWLazyPropertyWithInit(ISPickerView, delayPicker, {
    _delayPicker.selectBlock = ^(id item, NSInteger row) {
    };
    @weakify(self)
    _delayPicker.completeBlock = ^(id item, NSInteger row) {
        @strongify(self)
        [ISRingServer shareInstance].config.delayTime = [item[@"obj"] integerValue];
        [self loadData];
    };
})

@end
